
<template>
    <div>
  
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>查询表格</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="formInline" class="user-search">
        <el-form-item label="规则编号：">
          <el-input size="small" v-model="formInline.deptName" placeholder="请输入规则编号"></el-input>
        </el-form-item>
  
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search"
            style="background-color: rgb(0, 84, 254);">搜索</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="reset()" style="background-color: white;">重置</el-button>
        </el-form-item>
      </el-form>
      <!--列表-->
      <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
        style="width: 100%;">
        <el-table-column align="center" type="selection" width="60">
        </el-table-column>
        <el-table-column sortable prop="Id" label="规则编号" width="200">
        </el-table-column>
        <el-table-column sortable prop="Name" label="标题" width="200">
        </el-table-column>
        <el-table-column sortable prop="FillNumer" label="填写人数" width="150"></el-table-column>
  
        <el-table-column sortable prop="State" label="状态" width="140">
  
  
        </el-table-column>
        <el-table-column sortable prop="CreatedTime" label="更新时间" width="200">
        <!-- <template slot-scope="scope">
            <div>{{scope.row.editTime|timestampToTime}}</div>
            </template> -->
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="150">
          <template slot-scope="scope">
  
            <el-button size="mini" @click="write(scope.$index, scope.row)"
              style="background-color: white;color: rgba(0, 84, 254);border: none;font-weight: bold;">填写</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
    background
    layout="prev, pager, next"
    :total="1000" @current-change="pagefn">
  </el-pagination>
      
  
  
      <el-drawer :title="survey.title" :visible.sync="drawer" :direction="direction" size="30%" :before-close="handleClose">
        <div class="fill-survey">
  
          <el-form :model="answers" label-width="200px" ref="form">
            <template v-for="(question, index) in survey.Questions">
              
              <el-card class="question-card" :key="index">
                <header>
                  <span>第 {{ index + 1 }} 题</span>
                 
                </header>
  
                <el-form-item :label="question.Content">
                  <template v-if="question.QuestionType === 'SingleChoice'">
                    
                    <el-radio-group v-model="answers[index]">
                      <template v-for="(option, optionIndex) in question.Options">
  
                        <el-radio :key="optionIndex" :label="option.Value">{{ option.Value }}</el-radio>
                      </template>
                    </el-radio-group>
                  </template>
  
                  <template v-if="question.QuestionType === 'OpenEnded'">
                    <el-input v-model="answers[index]" type="textarea"></el-input>
                  </template>
                </el-form-item>
              </el-card>
            </template>
          </el-form>
          <div class="buttons">
            <el-button type="primary" @click="submitForm('form')" style="margin-top: 20px;margin-left: 20px;">提交</el-button>
            <!-- <el-button @click="resetForm('form')">重置</el-button> -->
          </div>
        </div>
      </el-drawer>
    </div>
  </template>
  
  <script>
  import Axios from 'axios'
  import { deptList, deptSave, deptDelete } from '../../api/userMG'

  export default {
    data() {
  
      return {
        writeId: '',
        checkList: [],
        survey: {
          title: '测试问卷',
          tempindex: '',
          Questions: [
            [
  
            ]
          ]
        },
        answers: [],
        tempAnswer: [],
        textarea: '',
        drawer: false,
        direction: 'rtl',
        radio: '1',
        nshow: true, //switch开启
        fshow: false, //switch关闭
        loading: false, //是显示加载
        editFormVisible: false, //控制编辑页面显示与隐藏
        title: '添加',
        editForm: {
          deptId: '',
          deptName: '',
          Description: '',
          token: localStorage.getItem('logintoken')
        },
        
        formInline: {
          page: 1,
          limit: 10,
          varLable: '',
          varName: '',
          token: localStorage.getItem('logintoken')
        },
        // 删除
        seletedata: {
          ids: '',
          token: localStorage.getItem('logintoken')
        },
        userparm: [], //搜索权限
        listData: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        }
      }
    },
    // 注册组件
  
    /**
     * 数据发生改变
     */
  
    /**
     * 创建完毕
     */
    created() {
      this.getdata(this.formInline)
    },
  
    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      async pagefn(val){
        const token = localStorage.getItem("token")
        let res1 = await Axios({
          method: 'get',
          url: this.$baseURL+'/Survey?pageIndex='+val+'&pageSize=10',
          headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
        })
        this.listData = res1.data
      },
      async write(index) {
        this.writeId = this.listData[index].Id
        localStorage.setItem('write', this.writeId)
        console.log(this.listData[index].Id)
        this.drawer = true
        const token = localStorage.getItem("token")
        let res1 = await Axios({
          method: 'get',
          url: this.$baseURL+`/Survey/Detail?Id=${this.writeId}`,
          headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
        })
        this.survey.Questions = res1.data.Questions
        this.survey.title = res1.data.Name
        console.log(res1.data.Questionst)
      },
  
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => { });
      },
      // 获取列表
      async getdata(parameter) {
        this.loading = true
        const token = localStorage.getItem("token")
        let res1 = await Axios({
          method: 'get',
          url: this.$baseURL+'/Survey?pageIndex=1&pageSize=10',
          headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
        })
        console.log(res1)
        // 模拟数据开始
        let res = {
          code: 0,
          msg: null,
          count: 5,
          data: [
            {
              addUser: '运行1',
              editUser: 100,
              addTime: 1521062371000,
              editTime: 2,
              deptId: 2,
              deptName: '3452',
              deptNo: '描述',
              parentId: 1
            },
            {
              addUser: '运行中',
              editUser: 200,
              addTime: 1521063247000,
              editTime: 1526652291000,
              deptId: 3,
              deptName: '2323',
              deptNo: '描述',
              parentId: 1
            },
            {
              addUser: '运行中',
              editUser: 200,
              addTime: 1526349555000,
              editTime: 1526349565000,
              deptId: 12,
              deptName: '4332',
              deptNo: '描述',
              parentId: 1
            },
            {
              addUser: '运行中',
              editUser: 500,
              addTime: 1526373178000,
              editTime: 1526373178000,
              deptId: 13,
              deptName: '5766',
              deptNo: '描述',
              parentId: 1
            },
            {
              addUser: '运行中',
              editUser: 400,
              addTime: 1526453107000,
              editTime: 1526453107000,
              deptId: 17,
              deptName: '3344',
              deptNo: '描述',
              parentId: 1
            },
  
          ]
        }
        this.loading = false
        this.listData = res1.data
        this.pageparm.currentPage = this.formInline.page
        this.pageparm.pageSize = this.formInline.limit
        this.pageparm.total = res.count
  
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getdata(this.formInline)
      },
      // 搜索事件
      search() {
        this.getOne(this.formInline)
      },
      async getOne(parameter){
        console.log(parameter)
        const token = localStorage.getItem("token")
        let res1 = await Axios({
          method: 'get',
          url:  this.$baseURL+`/Survey/One?Id=${parameter.deptName}`,
          headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
        })
        this.listData = []
        this.listData[0] = res1.data
        // console.log(res1.data)
      },

      // 删除
      deleteUser(index, row) {
  
      },
      // 关闭编辑、增加弹出框
      closeDialog() {
        this.editFormVisible = false
      },
      async reset(){
        const token = localStorage.getItem("token")
  let res2 = await Axios({
        method: 'get',
        url: this.$baseURL+'/Survey?pageIndex=1&pageSize=10',
        headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
      })
  
      this.listData = res2.data
  },
      submitForm(formName) {
        this.$refs[formName].validate(async valid => {
          if (valid) {
            let targetArray = this.answers.map(str => ({ answer: str }))
            const idArray = this.survey.Questions.map(({ Id }) => Id)
            const resultArray = targetArray.map(({ answer }, i) => ({ answer, QuestionId: idArray[i] }))
            let result = {}
            result.Answers = resultArray
            result.SurveyId = localStorage.getItem('write')
            console.log(result)
            const token = localStorage.getItem("token")
            let res1 = await Axios.post(this.$baseURL+'/Survey/Submit', result, {
              headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
            })
            
            this.drawer = false
            let res2 = await Axios({
              method: 'get',
              url: this.$baseURL+'/Survey?pageIndex=1&pageSize=10',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
              },
            })
            this.listData = res2.data
            this.$message({
                    type: 'success',
                    message: '填写成功！'
              })
  
  
  
  
            // 发送请求，将用户填写的答案保存至数据库
          } else {
            console.log('表单无效');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
  
    }
  }
  </script>
  
  <style scoped>
  .user-search {
    margin-top: 20px;
  }
  
  .userRole {
    width: 100%;
  }
  
  .el-form-item__label-wrap {
    margin-left: 0px !important;
  }
  
  /deep/ .el-form-item__label {
    text-align: left !important;
  }
  </style>
  
   
   